package com.victualler.core.common.utils;

import com.victualler.core.common.enums.ChecKDataErrorEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Aouthor Guoshichang
 * @Date 12:44 on 2018/7/12.
 * @Function 可以发送http请求 获取请求结果
 */
public class HttpUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * @author Guoshichang
     * @since 14:22 on 2018/7/12.
     * @param targetURL 请求地址
     * @param requestContent 字符类型请求内容
     * @Function  发送http请求并反馈String结果
     */
    public static String postRequest(String targetURL, String requestContent){
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.getBytes("UTF-8"));
            return postRequest(targetURL,inputStream,null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.RUN_ERROR,e.getMessage());
        }
    }

    /**
     * @author Guoshichang
     * @since 14:22 on 2018/7/12.
     * @param targetURL 请求地址
     * @param requestContent 请求内容
     * @Function  发送Json入参的http请求并反馈String结果
     */
    public static String postJsonRequest(String targetURL, String requestContent){
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.getBytes("UTF-8"));
            //调服务发请求
            return postRequest(targetURL,inputStream,"application/json;charset=UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.RUN_ERROR,e.getMessage());
        }
    }


    /**
     * @author Guoshichang
     * @since 12:57 on 2018/7/12.
     * @param targetURL 请求地址
     * @param inputStream 向服务端发送的内容 可以是文件流可以是字符流
     * @param contentType 请求类型 如 application/json 可为空
     * @Function 发送http请求获取String结果
     */
    public static String postRequest(String targetURL,InputStream inputStream,String contentType) {
        try {
            URL targetUrl = new URL(targetURL);
            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setUseCaches(false);
            httpConnection.setRequestMethod("POST");
            if(contentType!=null){
                httpConnection.setRequestProperty("Content-Type",contentType);
            }
            OutputStream outputStream = httpConnection.getOutputStream();
            if(inputStream != null){
                byte[] bytes = new byte[1024];
                int len = 0 ;
                while( (len = inputStream.read(bytes)) > 0){
                    outputStream.write(bytes, 0, len);
                }
                inputStream.close();
                outputStream.flush();
            }
            //获取响应
            if (httpConnection.getResponseCode() != 200) {
                throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.CALL_ERROR,"Failed : HTTP error code : "
                        + httpConnection.getResponseCode() + " message: "+httpConnection.getResponseMessage());
            }
            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
            String readLineStr;
            StringBuffer outStr  = new StringBuffer();
            while ((readLineStr = responseBuffer.readLine()) != null) {
                outStr.append(readLineStr) ;
            }
            httpConnection.disconnect();
            return outStr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.CALL_ERROR,e.getMessage());
        }
    }

    /**
     * @author Guoshichang
     * @since 19:54 on 2018/7/12.
     * @param url 远程url地址
     * @param savePath 保存路径
     * @Function
     */
    public static  File downLoadResourceByUrl(String url,String savePath){
        File file = new File(savePath);
        byte[] bytes = new byte[1024];
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            URLConnection conn = new URL(url).openConnection();
            InputStream in = conn.getInputStream();;
            OutputStream out = new FileOutputStream(file) ;
            int len = 0 ;
            while( (len = in.read(bytes)) > 0){
                out.write(bytes, 0, len);
            }
            out.flush();
            out.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            throw ChecKDataErrorEnum.createException(ChecKDataErrorEnum.CALL_ERROR,e.getMessage());
        }
    }


}
